<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\controller\Api;
use app\common\model\FishingGroundOrdersGroups;
use think\Controller;
use think\Db;
use think\Request;


class Fishinggroundorders extends Api
{
    private static $model;
//    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\common\model\FishingGroundOrders();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function lists()
    {
        $pageSize = input('pagesize', 15);

        // 2为待核销，5为已核销
        $status = input('status', 2);
        if (!in_array($status, [2, 5])) {
            $this->error('参数非法！');
        }

        $userId = $this->auth->id;
        $where = [
            'status' => $status,
            'user_id' => ['like', '%,' . $userId . ',%']
        ];

        $list = self::$model->where($where)->order('paytime desc')->paginate($pageSize);
        if ($list) {
            $fishing_ground_types = config('site.fishing_ground_types');
            $fish_types = config('site.fish_types');
            foreach ($list as $val) {
                $val->ground_info = \app\common\model\FishingGround::field('address,name,image')->where('id', $val->ground_id)->find();
                $positionId = $val->position_ids;
                if ($val->order_type == 2) {
                    // 拼团
                    $positionId = FishingGroundOrdersGroups::where('order_id', $val->id)->where('user_id', $userId)->value('position_id');
                }
                $positionName = \app\common\model\FishingGroundPositions::where('id', $positionId)->value('name');
                $val->position_name = $positionName;

                $fishing_ground_type = \app\common\model\FishingGroundTypes::where('id', $val->types_id)->value('type');
                $val->fish_type_name = $fishing_ground_types[$fishing_ground_type];

                $fish_type = \app\common\model\FishingGroundFishs::where('id', $val->fishs_id)->value('type');
                $val->fish_name = $fish_types[$fish_type];
            }
        }

        $this->success('预约记录', $list);
    }

    /**
     * 分享拼团订单详情
     */
    public function shareDetail()
    {
        $id = input('id');
        $row_info = self::$model->find($id);

        // 条件判断
        if (!$row_info) {
            $this->error('该拼团订单不存在！');
        }

        if ($row_info->order_type != 2) {
            $this->error('该订单非拼团订单！');
        }

        if ($row_info->status != 1) {
            $this->error('该订单不可拼团！');
        }

        $group_hours = config('site.group_hours') * 3600;
        $now = time();
        if ($row_info->paytime + $group_hours <= $now) {
            self::$model->groupFail($row_info->id);
            $this->error('已超时，不可参与！');
        }

        if ($row_info->group_nums >= $row_info->group_total_nums) {
            self::$model->groupSucess($row_info->id);
            $this->error('拼团人数已超过限制！');
        }

        $userId = $this->auth->id;
        $userIds = FishingGroundOrdersGroups::where('order_id', $id)->where('status', 1)->column('user_id');
        if (in_array($userId, $userIds)) {
            $this->error('你已参与拼团！');
        }

        // 返回数据
        $fishs_id = \app\common\model\FishingGroundPositions::where('id', $row_info->position_id)->value('fishs_id');
        $fishsInfo = \app\common\model\FishingGroundFishs::where('id', $fishs_id)->find();
        $priceInfo = \app\common\model\FishingGroundPrices::where('ground_id', $fishsInfo->ground_id)->where('type', $fishsInfo->type)->find();
        $row_info->prices = $priceInfo;

        $fish_types = config('site.fish_types');
        $row_info->fish_name = $fish_types[$fishsInfo->type];

        $fishing_ground_types = config('site.fishing_ground_types');
        $typeInfo = \app\common\model\FishingGroundTypes::where('id', $fishsInfo->types_id)->find();
        $row_info->type_name = $fishing_ground_types[$typeInfo->type];

        $groundInfo = \app\common\model\FishingGround::where('id', $fishsInfo->ground_id)->find();
        $row_info->ground = $groundInfo;

        $apply_hours = config('site.apply_hours');
        $hours = $apply_hours[$row_info->time_id];
        $row_info->hours = $hours;

        $deadTime = $group_hours * 3600 - ($now - $row_info->paytime);
        $row_info->dead_time = $deadTime;

        $row_info->start_time = date('H:i', $row_info->start_time);
        $row_info->end_time = date('H:i', $row_info->end_time);

        $group_cates = config('site.group_cates');
        $group_type_name = $group_cates[$row_info->group_type];
        $row_info->group_type_name = $group_type_name;

        $positions = $fishsInfo->positions;
        $row_info->positions = $positions;

        $this->success('订单详情', $row_info);
    }

    /**
     * 加入拼团
     */
    public function joinGroups()
    {
        $id = input('id');
        $row_info = self::$model->find($id);

        // 条件判断
        if (!$row_info) {
            $this->error('该拼团订单不存在！');
        }

        if ($row_info->order_type != 2) {
            $this->error('该订单非拼团订单！');
        }

        if ($row_info->status != 1) {
            $this->error('该订单不可拼团！');
        }

        $group_hours = config('site.group_hours') * 3600;
        $now = time();
        if ($row_info->paytime + $group_hours <= $now) {
            self::$model->groupFail($row_info->id);
            $this->error('已超时，不可参与！');
        }

        if ($row_info->group_nums >= $row_info->group_total_nums) {
            self::$model->groupSucess($row_info->id);
            $this->error('拼团人数已超过限制！');
        }

        $positionId = input('position_id');
        $posInfo = \app\common\model\FishingGroundPositions::find($positionId);
        if (!$posInfo) {
            $this->error('该钓位不存在！');
        }

        if ($posInfo->status != 0) {
            $this->error('该钓位不可预约！');
        }

        $userId = $this->auth->id;
        $userIds = FishingGroundOrdersGroups::where('order_id', $id)->where('status', 1)->column('user_id');
        if (in_array($userId, $userIds)) {
            $this->error('你已参与拼团！');
        }

        // 拼团记录
        $orderNum = create_order($positionId);
        $gdata = [
            'user_id' => $userId,
            'order_num' => $orderNum,
            'position_id' => $positionId,
            'order_id' => $id,
            'group_type' => $row_info->group_type,
            'price' => $row_info->price,
        ];

        $res = FishingGroundOrdersGroups::create($gdata);
        if (!$res->id) {
            $this->error('记录生成失败！');
        }
        $this->success('记录生成成功', ['order_num' => $orderNum, 'position_id' => $id]);
    }

    /**
     * 订单支付
     */
    public function pay()
    {
        $userId = $this->auth->id;
        $orderNum = input('order_num');
        $row_info = self::$model->where('order_num', $orderNum)->find();
        if (!$row_info) {
            $this->error('参数错误！');
        }

        if ($row_info->order_type == 1) {
            if ($row_info->status != 0) {
                $this->error('该订单不可支付！');
            }
        } elseif ($row_info->order_type == 2) {
            if (!in_array($row_info->status, [0, 1])) {
                $this->error('该订单不可支付！');
            }
        } else {
            $this->error('不可支付！');
        }

        $positionId = input('position_id');
        $posInfo = \app\common\model\FishingGroundPositions::find($positionId);
        if (!$posInfo) {
            $this->error('该钓位不存在！');
        }

        if ($posInfo->status != 0) {
            $this->error('该钓位不可预约！');
        }

        $group_hours = config('site.group_hours') * 3600;
        $now = time();
        if ($row_info->paytime + $group_hours <= $now) {
            self::$model->groupFail($row_info->id);
            $this->error('已超时，拼团失败！');
        }

        if ($row_info->group_nums >= $row_info->group_total_nums) {
            self::$model->groupSucess($row_info->id);
            $this->error('拼团人数已超过限制！');
        }
//            $now = date('Y-m-d H:i:s', time());

        $userIds = FishingGroundOrdersGroups::where('order_id', $row_info->id)->where('status', 1)->column('user_id');
        if (in_array($userId, $userIds)) {
            $this->error('你已参与拼团！');
        }

        Db::startTrans();
        try {
            $openIdApp = \app\common\model\User::where('id', $userId)->value('open_id_app');
            $openIdApplet = \app\common\model\User::where('id', $userId)->value('open_id_applet');

            $third_config = include(APP_PATH . 'third.php');
            $pay_type = $row_info->pay_type;
            switch ($pay_type) {
                case 1:
                    $type = "alipay";
                    break;
                case 2:
                    $type = "wechat";
                    break;
            }
            $params = [
                'amount' => $row_info->money,
                'orderid' => $row_info->order_num,
                'type' => $type,
                'title' => '预约成功',
                'notifyurl' => $third_config['notify_url'],
                'method' => "miniapp",
                'auth_code' => ""
            ];

            // 以微信支付为例
            $platformType = $row_info->platform_type;
            if ($platformType == 2) {
                $params['method'] = 'mp';
//                $params['openid'] = $openIdWechat;
            } elseif ($platformType == 1) {
                $params['method'] = 'miniapp';
                $params['openid'] = $openIdApplet;
            } elseif ($platformType == 3) {
                $params['method'] = 'wap';
                $params['openid'] = $openIdApp;
            } elseif ($platformType == 4) {
                $params['method'] = 'app';
                $params['openid'] = $openIdApp;
            }

            $res = Service::submitOrder($params);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('支付数据！', $res);
    }

    /**
     * 拼团订单详情
     */
    public function read()
    {
        $id = input('id');
        $row_info = self::$model->find($id);
        if (!$row_info) {
            $this->error('该拼团订单不存在！');
        }

        if ($row_info->order_type != 2) {
            $this->error('该订单非拼团订单！');
        }

        if ($row_info->status != 1) {
            $this->error('该订单不可拼团！');
        }

        $group_hours = config('site.group_hours') * 3600;
        $now = time();
        if ($row_info->paytime + $group_hours <= $now) {
            self::$model->groupFail($row_info->id);
            $this->error('已超时，拼团失败！');
        }

        if ($row_info->group_nums >= $row_info->group_total_nums) {
            self::$model->groupSucess($row_info->id);
            $this->error('拼团人数已超过限制！');
        }

        $fishs_id = \app\common\model\FishingGroundPositions::where('id', $row_info->position_id)->value('fishs_id');
        $fishsInfo = \app\common\model\FishingGroundFishs::where('id', $fishs_id)->find();

        $groundInfo = \app\common\model\FishingGround::where('id', $fishsInfo->ground_id)->find();
        $row_info->ground = $groundInfo;

        $groups = $row_info->groups;
        if ($groups) {
            foreach ($groups as $val) {
                $val->avatar = \app\common\model\User::where('id', $val->user_id)->value('avatar');
            }
        }

        $deadTime = $group_hours - ($now - $row_info->paytime);
        $row_info->dead_time = $deadTime;

        $userId = $this->auth->id;
        $userIds = FishingGroundOrdersGroups::where('order_id', $id)->where('status', 1)->column('user_id');
        $isPin = false;
        if (in_array($userId, $userIds)) {
            $isPin = true;
        }

        $row_info->is_pin = $isPin;

        $this->success('拼团订单详情', $row_info);
    }

    /**
     * 取消订单
     */
    public function cancleOrder()
    {
        $userId = $this->auth->id;
        $orderNum = input('order_num');
        $row_info = self::$model->where('order_num', $orderNum)->find();
        if (!$row_info) {
            $this->error('参数错误！');
        }

        if ($row_info->start_time <= time()) {
            $this->error('订单已开始生效，不可取消！');
        }

        if ($row_info->order_type == 2) {
            $userIds = explode(',', trim($row_info->user_id, ','));
            $mainUserId = reset($userIds);
            if ($userId == $mainUserId) {
                $this->error('订单发起人不可取消订单！');
            }
        }

        // 启动事务
        Db::startTrans();
        try {

            if ($row_info->order_type == 1) {
                // 单独
                $userId = trim($row_info->user_id);
                $row_info->status = 4;
                $row_info->save();
                // 退款
                switch ($row_info->pay_type) {
                    case 1:
                        // 支付宝退款
                        break;
                    case 2:
                        // 微信退款
                        break;
                    case 3:
                        // 余额退款
                        break;
                }

                // 释放钓位
                FishingGroundPositions::where('id', $row_info->position_id)->update(['status' => 0]);

            } elseif ($row_info->order_type == 2) {
                // 拼团
                FishingGroundOrdersGroups::cancleOrder($row_info->id, $userId);

                $row_info->group_nums -= 1;
                if ($row_info->status == 2) {
                    $row_info->status = 1;
                    $row_info->grouptime = 0;
                }
                $row_info->save();
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
    }
}
